// 交易结算状态管理
const settlement = {
  state: {
    assignedGoodsList: []
  },
  getters: {
    assignedGoodsList: state => state.assignedGoodsList,  //已经分摊的商品额度
  },

  mutations: {
    SET_ASSIGNED_GOODS_LIST: (state, val) => {
      state.assignedGoodsList = val;
    },
  },

  actions: {
    InitData({commit}) {
      return new Promise((resolve, reject) => {
        commit('SET_ASSIGNED_GOODS_LIST', [])
        resolve()
      })
    },
    CaclExistList({commit}, list) {
      // 按商品项归类
      let newList = []
      list.forEach(item => {
        let status = newList.find(el => el.codeTs === item.codeTs) // 判断第一层级，用codeTs属性来判断
        if (status) {
          status.children.push({...item}) // 将数据插入到第二层级中
        } else {
          let obj = {codeTs: item.codeTs, children: [{...item}]}
          newList.push(obj)
        }
      })
      // 计算已添加的边民所分摊了的额度
      let result = newList.map(item => {
        let buyAmountTotal = item.children.reduce((pre, item) => {
          return pre + item.buyAmount;
        }, 0)
        let buyQtyTotal = item.children.reduce((pre, item) => {
          return pre + item.buyQty;
        }, 0)
        let netWtTotal = item.children.reduce((pre, item) => {
          return pre + item.netWt;
        }, 0)
        let grossWtTotal = item.children.reduce((pre, item) => {
          return pre + item.grossWt;
        }, 0)
        let buyQty1Total = item.children.reduce((pre, item) => {
          return pre + item.buyQty1;
        }, 0)
        let buyQty2Total = item.children.reduce((pre, item) => {
          return pre + item.buyQty2;
        }, 0)

        return {
          buyAmountTotal,
          buyQtyTotal,
          netWtTotal,
          grossWtTotal,
          buyQty1Total,
          buyQty2Total,
          ...item
        }
      })
      commit('SET_ASSIGNED_GOODS_LIST', result)
    }
  }
}

export default settlement
